<template>
  <div class="app-container">
    <div class="control-panel">
      <el-button @click="resetView">🔄 还原视图</el-button>
      <span class="status">{{ statusText }}</span>
    </div>
    <el-row :gutter="20">
      <el-col :span="4">
          <el-card  shadow="hover"  v-for=" switchItem in switchAndLineList " v-if=" switchItem.switchInfo " class="el-card-switch">
            <div slot="header" class="clearfix">
              <span>{{switchItem.switchInfo.switchName}}</span>
              <el-switch style="float: right; padding: 3px 0" @change="controlSwitch(switchItem.switchInfo)"
                         v-model="switchItem.switchInfo.status === 'OPEN'"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </div>
            <div>
              <div v-if="switchItem.switchInfo.status === 'OPEN'">
                <div class="switch-status-text switch-status-open">当前是开启状态</div>
                <div class="switch-time">操作说明：{{ switchItem.switchInfo.ext }}</div>
                <div class="switch-time">开启时间：{{switchItem.switchInfo.operatorTime}}</div>
              </div>
              <div v-else-if=" switchItem.switchInfo.status === 'CLOSE'">
                <div class="switch-status-text switch-status-close">当前是关闭状态</div>
                <div class="switch-time">操作说明：{{ switchItem.switchInfo.ext }}</div>
                <div class="switch-time">关闭时间：{{switchItem.switchInfo.operatorTime}}</div>
              </div>
              <div v-else>
                <div class="switch-status-text switch-status-other">开关当前禁止操作</div>
              </div>
            </div>

<!--            <template v-for=" switchItem in switchAndLineList ">-->
<!--              <template v-if=" switchItem.switchInfo ">-->
<!--                <div>{{switchItem.switchInfo.switchName}}</div>-->

<!--                <el-divider></el-divider>-->
<!--              </template>-->
<!--            </template>-->
          </el-card>
      </el-col>
      <el-col :span="20">
        <div id="container" ref="container">
          <svg id="svg-container" ref="svg_container" xmlns="http://www.w3.org/2000/svg"
               style="width: 33.1102in;height: 23.3858in;" viewBox="0 0 2383.94 1683.78" :style="{
          transform: `translate(${viewState.x}px, ${viewState.y}px) scale(${viewState.scale})`,
          cursor: svgCursor
        }">
            <image id="background" :href="drawingUrl" width="100%" preserveAspectRatio="xMidYMid meet"></image>
            <line
              v-for="line in lines"
              :class="line.className"
              :line-code="line.lineCode"
              :line_name="line.lineName"
              :key="line.key"
              :x1="line.x1"
              :y1="line.y1"
              :x2="line.x2"
              :y2="line.y2"
              :stroke="line.color">
            </line>
          </svg>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      :title="controlSwitchForm.cmd === 'OPEN' ? '打开电路' : '关闭电路'"
      :visible.sync="controlSwitchDialogVisible"
      width="30%"
    >
      <el-form ref="controlSwitchForm" :model="controlSwitchForm" :rules="controlSwitchFormRules" label-width="80px">
        <el-form-item label="确认人员" prop="confirmerName">
          <el-input v-model="controlSwitchForm.confirmerName" placeholder="请输入确认人员" />
        </el-form-item>
        <el-form-item label="操作说明" prop="remark">
          <el-input v-model="controlSwitchForm.remark" type="textarea" placeholder="请输入本次操作说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitControlSwitchForm">确 定</el-button>
        <el-button @click="cancelControlSwitchForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStation_drawingByUser } from "@/api/system/station_drawing"
import { control } from "@/api/system/catenary_switch"

import { getCatenary_switchByDrawingId,getCatenary_switchAndLinesByDrawingId }  from "@/api/system/catenary_switch"
import {addSingle_line_annotation, updateSingle_line_annotation} from "@/api/system/single_line_annotation";


export default {
  name: "catenary_switch_control",
  dicts: ['biz_line_type', 'biz_t_f'],
  data() {
    return {
      // 遮罩层
      loading: true,
      //
      drawingInfo:{},
      statusText: '就绪',
      svgCursor: '',
      drawingUrl:'',
      viewState: {x: 0, y: 0, scale: 1},
      isDragging: false,
      lastX: 0,
      lastY: 0,
      isAnnotating: false,
      tempLine: null,
      startPoint: null,
      switchAndLineList:[],
      switchList:[],
      lines:[],
      controlSwitchDialogVisible:false,
      controlSwitchForm:{},
      controlSwitchFormRules:{
        confirmerName:[
          { required: true, message: "确认人员不能为空", trigger: "blur" }
        ],
        remark:[{
          required: true, message: "操作说明不能为空", trigger: "blur"
        }]
      }
    }
  },
  computed: {
    container() {
      return this.$refs.container
    },
    svgContainer() {
      return this.$refs.svg_container
    }

  },
  mounted() {
    this.container.addEventListener('wheel', this.containerWheel, true); //滚轮缩放
    this.svgContainer.addEventListener('mousedown', this.svgContainerMousedown, true); // 拖拽
    document.addEventListener('mousemove', (e) => {
      if (!this.isDragging) return;
      this.viewState.x = e.clientX - this.lastX;
      this.viewState.y = e.clientY - this.lastY;
    });
    document.addEventListener('mouseup', () => {
      this.isDragging = false;
      this.svgCursor = this.svgCursor ? 'crosshair' : 'grab';
    });
  },
  beforeMount() {
    // window.addEventListener('resize', this.updateTransform)
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.updateTransform)
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据 获取站点图纸
    initData(){
      getStation_drawingByUser().then(response => {
        if(response?.data && response.data.length >=1){
          this.drawingUrl = process.env.VUE_APP_BASE_API + response.data[0].basicDrawingInfo;
          this.drawingInfo = response.data[0];
          this.getSwitchAndLineList();
          this.getSwitchList();
        }

      })
    },
    getSwitchList(){
      getCatenary_switchByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if(response?.data){
          this.switchList = response.data;
        }
      })
    },
    getSwitchAndLineList(){
      getCatenary_switchAndLinesByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if(response?.data){
          this.switchAndLineList = response.data;
          this.processedLines();
        }
      })
    },
    processedLines() {
      const _lines = [];
      this.switchAndLineList.forEach((switchLine, index) => {
        switchLine.lineList?.forEach((line, lineIndex) => {
          let color = line.lineColor;
          let className = 'svg-line ';

          if (switchLine.switchInfo) {
            if (switchLine.switchInfo.status === "OPEN") {
              color = switchLine.switchInfo.openColor;
              className += 'blink-line-css';
            } else if (switchLine.switchInfo.status === "CLOSE") {
              color = switchLine.switchInfo.closeColor;
            }
          }

          _lines.push({
            ...line,
            color,
            className,
            key: `line-${index}-${lineIndex}`
          });
        });
      });
      this.lines = _lines;

    },
    controlSwitch(e){
      let cmd = "";
      if(e.status === "OPEN"){
        cmd = "CLOSE";
      }else if(e.status === "CLOSE"){
        cmd = "OPEN";
      }else{
        this.$modal.msgWarning("该开关禁止操作，请联系管理员");
        return ;
      }
      this.controlSwitchForm ={
        id:e.id,
        cmd:cmd,
        confirmerName:"",
        remark:""
      }
      this.controlSwitchDialogVisible = true;

    },
    submitControlSwitchForm(){
      this.$refs["controlSwitchForm"].validate(valid => {
        if (valid) {
          control(this.controlSwitchForm).then(response => {
            this.$modal.msgSuccess("操作成功")
            this.controlSwitchDialogVisible = false
            this.initData();
          })
        }
      })
    },
    cancelControlSwitchForm(){
      this.controlSwitchDialogVisible = false
    },
    containerWheel(e) { // 中心底图缩放事件

      e.preventDefault();
      const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
      const newScale = this.viewState.scale * scaleFactor;

      if (newScale < 0.3 || newScale > 10) return;

      const rect = this.container.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      this.viewState.x -= (mouseX - this.viewState.x) * (scaleFactor - 1);
      this.viewState.y -= (mouseY - this.viewState.y) * (scaleFactor - 1);
      this.viewState.scale = newScale;
    },
    svgContainerMousedown(e) { // 中心底图拖拽事件
      if (this.isAnnotating || e.target.classList.contains('line')) return;
      this.isDragging = true;
      this.lastX = e.clientX - this.viewState.x;
      this.lastY = e.clientY - this.viewState.y;
      this.svgCursor = 'grabbing';
    },
    resetView() { // 还原试图
      this.viewState = {x: 0, y: 0, scale: 1};
    },

  }
}
</script>

<style scoped lang="scss">
body {
  margin: 0;
  padding: 20px;
  font-family: Arial, sans-serif;
  overflow: hidden;
}

#container {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  overflow: hidden;
  position: relative;
  touch-action: none;
}

#svg-container {
  width: 100%;
  height: 100%;
  cursor: grab;
  //background-color: #f8f8f8;
}

#svg-container:active {
  cursor: grabbing;
}

.svg-line {
  stroke-width: 6;
  //stroke-dasharray: 5, 5;
  fill: none;
}

.svg-line:hover {
  stroke-width: 8;
  stroke: aqua;
}

.temp {
  stroke: blue;
  stroke-dasharray: 4, 4;
}

.control-panel {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

button {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

select, input {
  padding: 8px;
  font-size: 14px;
}

.status {
  font-size: 14px;
  color: #555;
  margin-left: auto;
}
.clearfix{
  font-weight: bold;
}
.el-card-switch{
  margin-bottom: 10px;
}
.switch-status-text{
  line-height: 26px;
  font-size: 14px;
}
.switch-time{
  color: #909399;
  font-size: 13px;
}
.switch-status-open{
  color: #67C23A;
}
.switch-status-close{
  color: #F56C6C;
}
.switch-status-other{
  color: #E6A23C;
}
/* 为线条定义闪烁动画 */
//.blink-line-css {
//  animation: blink-animation 1s infinite;
//}
//
//@keyframes blink-animation {
//  0% {
//    stroke: #fa0f0f; /* 初始颜色 */
//    opacity: 1;
//  }
//  50% {
//    stroke: #ccc1c1; /* 闪烁时颜色，可以在此更改 */
//    opacity: 0.3; /* 通过改变透明度实现闪烁 */
//  }
//  100% {
//    stroke: #2d0505;
//    opacity: 1;
//  }
//}
</style>
